﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Windows.Media.Imaging;
using Schuifpuzzel.Model;

namespace Schuifpuzzel.Persistence
{
    /// <summary>
    /// This class is responsible for serializing and deserializing the high scores
    /// </summary>
    static class MySerializer
    {
        private const string FileLocation = "HighScores.xml";

        /// <summary>
        /// Serialize a HighScoreList
        /// </summary>
        /// <param name="highScoreList">The list to be serialised</param>
        public static void Serialize(HighScoreList highScoreList)
        {
            
            Stream stream = null;
            try
            {
                stream = File.Open(FileLocation, FileMode.Create);
                //Opens a file and serializes the object into it in binary format.
                if(stream != Stream.Null)
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(stream, highScoreList);
                    stream.Close();  
                }
                
            }
            catch (Exception)
            {
                if(stream != null)
                {
                    stream.Close();
                }
            }
            

        }

        /// <summary>
        /// Deserializes the stored high scores
        /// </summary>
        /// <returns></returns>
        public static HighScoreList DeSerialize()
        {
            Stream stream = null;
            try
            {
                stream = File.Open(FileLocation, FileMode.OpenOrCreate);
                if (stream != Stream.Null)
                {
                    HighScoreList obj;

                    //Opens file "data.xml" and deserializes the object from it.
                    BinaryFormatter formatter = new BinaryFormatter();

                    obj = (HighScoreList)formatter.Deserialize(stream);
                    stream.Close();

                    return obj;   
                }
                
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex.Message);
                if(stream!=null)
                {
                    stream.Close();
                }
               
            }
            return null;
        }
    }
}
